document.addEventListener('DOMContentLoaded', () => {
  const form = document.getElementById('registerForm');

  const usernameInput        = document.getElementById('inputFirstName');
  const phoneInput           = document.getElementById('inputPhone');
  const passwordInput        = document.getElementById('inputPassword');
  const passwordConfirmInput = document.getElementById('inputPasswordConfirm');
  const submitBtn            = form.querySelector('button[type="submit"]');

  const allInputs = [
    usernameInput,
    phoneInput,
    passwordInput,
    passwordConfirmInput
  ];

  // 输入时隐藏/显示浮动标签，并清除/恢复校验提示
  allInputs.forEach(input => {
    input.addEventListener('input', () => {
      const lbl = input.parentElement.querySelector('label');
      if (input.value.length > 0) {
        lbl.style.visibility = 'hidden';
      } else {
        lbl.style.visibility = 'visible';
      }
      input.classList.remove('is-invalid');
      const fb = input.parentElement.querySelector('.invalid-feedback');
      if (fb) fb.textContent = '';
    });
  });

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    clearValidation();

    const username = usernameInput.value.trim();
    const phone    = phoneInput.value.trim();
    const password = passwordInput.value;
    const confirm  = passwordConfirmInput.value;

    let valid = true;

    if (!/^[A-Za-z0-9]{1,6}$/.test(username)) {
      showError(usernameInput, '用户名仅限字母或数字，且不超过 6 位');
      valid = false;
    }
    if (!/^\d{10,15}$/.test(phone)) {
      showError(phoneInput, '请输入 10 到 15 位数字的电话号码');
      valid = false;
    }
    if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(password)) {
      showError(passwordInput, '密码至少 8 位，且包含字母和数字');
      valid = false;
    }
    if (password !== confirm) {
      showError(passwordConfirmInput, '两次输入的密码不一致');
      valid = false;
    }
    if (!valid) return;

    submitBtn.disabled = true;
    const originalText = submitBtn.textContent;
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> 创建中...';

    const payload = { username, phone, password };
    try {
      const resp = await fetch('http://your_server_ip:8080/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      const result = await resp.json();
      if (result.success) {
        window.location.href = '../login.html';
      } else {
        alert(result.msg || '注册失败，请重试');
      }
    } catch (err) {
      console.error(err);
      alert('网络错误，无法连接到服务器');
    } finally {
      submitBtn.disabled = false;
      submitBtn.textContent = originalText;
    }
  });

  function clearValidation() {
    allInputs.forEach(input => {
      input.classList.remove('is-invalid');
      const fb = input.parentElement.querySelector('.invalid-feedback');
      if (fb) fb.textContent = '';
      const lbl = input.parentElement.querySelector('label');
      if (lbl) lbl.style.visibility = input.value.length > 0 ? 'hidden' : 'visible';
    });
  }

  function showError(input, message) {
    input.classList.add('is-invalid');
    const fb = input.parentElement.querySelector('.invalid-feedback');
    if (fb) fb.textContent = message;
    input.focus();
  }
});
